// pages/search_privacy/search_privacy.js
const app = getApp(), core = require('../../utils/core');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchTimer: 0,
    nav:0,
    show:false,
    searchList: [],
    checkedIndexes: [],
    value:'',//search word,
    addedList: [], //已经添加到黑名单的公司列表
  },
  check:function(e){
    let index = e.currentTarget.dataset.index;
    let findIndex = this.data.checkedIndexes.indexOf(index);
    if(findIndex===-1) {
      this.data.checkedIndexes.push(index);
    }else {
      this.data.checkedIndexes.splice(findIndex, 1);
    }
    this.setData({
      checkedIndexes: this.data.checkedIndexes
    })
  },
  value:function(e){
    let value = e.detail.value.trim();
    this.setData({
      value: value
    });
    if(value) {
      clearTimeout(this.data.searchTimer);
      this.data.searchTimer = setTimeout(this.goSearch,500);
      this.setData({loading: true});
    }
  },
  show:function(e){
    this.setData({
      show:!this.data.show
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onUnload() {
    this.getOpenerEventChannel().emit('dataTransfer', {addedList: this.data.addedList});
  },
  bindToggleCheckAll() {
    if(this.data.searchList.length===0) {
      return;
    }
    if(this.data.checkedIndexes.length===this.data.searchList.length) {
      //取消全选
      this.setData({checkedIndexes: []});
    }else {
      //全选
      let indexes = [];
      this.data.searchList.forEach((item,index)=>indexes.push(index));
      this.setData({checkedIndexes: indexes});
    }
  },
  goSearch() {
    core.get({
      url: "xilujob.company/search_company", loading:false, data: {q:this.data.value},
      success: ret => {
        this.setData({searchList: ret.data, loading:false, checkedIndexes:[]});
      }
    })
  },
  bindSubmit() {
    if(this.data.checkedIndexes.length===0) {
      return;
    }
    let ids = [];
    this.data.checkedIndexes.forEach(item=>{
      ids.push(this.data.searchList[item].id);
    });
    core.post({
      url: 'xilujob.company/set_blacklist_company', data:{company_ids: ids},
      success: ret => {
        let remainList = [];
        this.data.searchList.forEach((item,index)=>{
          if(this.data.checkedIndexes.indexOf(index)===-1) {
            remainList.push(item);
          }else {
            this.data.addedList.push(item);
          }
        });
        this.setData({searchList: remainList, checkedIndexes:[]});
      },
    });
  },


});
